package com.product.shopping.config;

import com.product.shopping.dao.ProductDao;
import com.product.shopping.entity.Product;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Scope;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

@Service
@Scope("singleton")
public class ApplicationListener implements org.springframework.context.ApplicationListener<ContextRefreshedEvent> {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    RedisService redisService;
    @Resource
    ProductDao productDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        if(contextRefreshedEvent.getApplicationContext().getParent() == null) {
            logger.info(">>>>>>>>>>>>项目初始化完成，执行监听器中逻辑");
            //mapper中的sql，返回全部上架（支持秒杀）的商品集合
            List<Product> list = productDao.queryList();
            Iterator<Product> it = list.iterator();
            while(it.hasNext()) {
                Product p = it.next();
                logger.info("商品ID："+p.getPid()+"商品库存："+p.getPnum());
                try {

                    redisTemplate.opsForValue().set(p.getPid(), p.getPnum());
                } catch (Exception e) {
                    logger.error("当前商品ID："+p.getPid()+"库存："+p.getPnum()+"放入Redis缓存异常<<<<<<<<<<<<<<<<<<<<");
                    e.printStackTrace();
                }
            }
        }

    }
}
